package com.example.controller;

import com.alibaba.fastjson2.JSONObject;
import com.example.config.MinioUtils;
import io.micrometer.core.annotation.Timed;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author thj
 * @date 2024-08-13
 */
@RestController
public class TestController {
    private final static Logger logger = LoggerFactory.getLogger(TestController.class);

    @Value("${minio.bucketName}")
    private String bucketName;

    @Resource
    private MinioUtils minioUtils;


    @PostMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile  ) throws Exception {
        logger.info("uploadFile  ---- 0 -----  start ");
        String imgPath = minioUtils.uploadFileSingle(bucketName, multipartFile);
        logger.info("uploadFile  ---- 1 -----  end {}",imgPath);
        return imgPath;
    }

    @GetMapping("/isObjectExist")
    public boolean isObjectExist(@RequestParam("fileName") String fileName) throws Exception {
        return minioUtils.isObjectExist(bucketName, fileName);
    }

    //Timed 通过访问http://localhost:18083/minio/ac/prometheus 获取调用该方法消耗时间
    @Timed("TestController.getFile")
    @GetMapping("/getFile")
    public String getFile(@RequestParam("fileName") String fileName) throws Exception {
        return minioUtils.getUploadObjectUrl(bucketName, fileName, 3600);
    }

    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception {
        minioUtils.download(bucketName, fileName, response);
    }

    @GetMapping("/removeFile")
    public boolean removeFile(@RequestParam("fileName") String fileName) {
        return minioUtils.removeObject(bucketName, fileName);
    }

    @Timed("TestController.removeFiles")
    @GetMapping("/removeFiles")
    public void removeFiles() throws Exception {
        minioUtils.removeObjects(bucketName);
    }

    @PostMapping("/uploadImgBase64")
    public String uploadImgBase64(@RequestBody String param) throws Exception {
        logger.info("uploadImgBase64  ---- 0 -----  start ");
        JSONObject paramObj = JSONObject.parseObject(param);
        String imgBase64 = paramObj.getString("imgBase64");
        String fileName = System.currentTimeMillis() + ".jpg";
        String imgUrl = minioUtils.uploadImgBase64(bucketName, imgBase64, fileName);
        logger.info("uploadImgBase64  ---- 1 -----  end {}", imgUrl);
        return imgUrl;
    }

}
